package readHandle

import (
	"chart.zozoo.net/app/dao/messageDao"
	"chart.zozoo.net/app/service/userService"
	"chart.zozoo.net/app/socket/connManage"
	"chart.zozoo.net/app/socket/writeHandle"
	"chart.zozoo.net/app/utils/commonFunc"
	"encoding/json"
	"time"
)

//获取聊天详情

type DetailsReq struct {
	FUuid    string `json:"f_uuid"`    //好友id
	LoadSize int    `json:"load_size"` //已加载数量
}
type DetailsRsp struct {
	FUuid   string    `json:"f_uuid"`   //好友id
	LoadAll bool      `json:"load_all"` //是否加载完毕
	List    []*Detail `json:"list"`     //聊天列表
}
type Detail struct {
	FromUid    string    `json:"from_uid"`
	ToUid      string    `json:"to_uid"`
	MsgType    string    `json:"msg_type"`
	MsgContent string    `json:"msg_content"`
	CreatedAt  time.Time `json:"created_at"`
}

func handleMessageDetails(msg, addr string) {
	//获取用户信息
	user := connManage.GetConn(addr).UserInfo
	conn := connManage.GetConn(addr).Conn

	details := new(DetailsReq)
	err := json.Unmarshal([]byte(msg), details)
	errMsg := ChatMessage{
		ToUid:   details.FUuid,
		MsgType: "errMsg",
	}
	if err != nil {
		errMsg.MsgContent = err.Error()
		writeHandle.WriteMessage(conn, errMsg)
		return
	}

	//获取用户信息
	friendInfo, err := userService.InfoByUuid(details.FUuid)
	if err != nil {
		errMsg.MsgContent = err.Error()
		writeHandle.WriteMessage(conn, errMsg)
		return
	}

	//获取消息id
	msgId := commonFunc.GenerateMsgId(user.Id, friendInfo.Id)

	rsp := new(DetailsRsp)
	rsp.List = make([]*Detail, 0)
	rsp.FUuid = details.FUuid

	//查询数据库
	list, err := messageDao.FindByMsgId(msgId, details.LoadSize, 20)
	if err != nil {
		errMsg.MsgContent = err.Error()
		writeHandle.WriteMessage(conn, errMsg)
		return
	}
	if len(list) < 20 {
		rsp.LoadAll = true
	}

	for _, v := range list {
		d := &Detail{
			FromUid:    v.FromUid,
			ToUid:      v.ToUid,
			MsgType:    v.MsgType,
			MsgContent: v.MsgContent,
			CreatedAt:  v.CreatedAt,
		}
		rsp.List = append(rsp.List, d)
	}

	//返回结果
	content, err := json.Marshal(rsp)
	if err != nil {
		errMsg.MsgContent = err.Error()
		writeHandle.WriteMessage(conn, errMsg)
		return
	}
	errMsg.MsgType = "messageDetails"
	errMsg.MsgContent = string(content)
	writeHandle.WriteMessage(conn, errMsg)
}
